package com.woniuxy.health.manager.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.health.manager.dto.RoleDto;
import com.woniuxy.health.manager.mapper.ManagerMapper;
import com.woniuxy.health.manager.mapper.ManagerRoleMapper;
import com.woniuxy.health.manager.mapper.RoleMapper;
import com.woniuxy.health.manager.mapper.RolePermissionMapper;
import com.woniuxy.health.model.manager.Manager;
import com.woniuxy.health.model.manager.ManagerRole;
import com.woniuxy.health.model.manager.Role;
import com.woniuxy.health.manager.service.IRoleService;
import com.woniuxy.health.model.manager.RolePermission;
import com.woniuxy.health.manager.vo.PageVo;
import com.woniuxy.health.manager.vo.RoleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author woniuxy
 * @since 2023-09-04
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    private final ManagerMapper managerMapper;
    private final RoleMapper roleMapper;
    private final ManagerRoleMapper managerRoleMapper;
    private final RolePermissionMapper rolePermissionMapper;

    @Autowired
    public RoleServiceImpl(ManagerMapper managerMapper, RoleMapper roleMapper, ManagerRoleMapper managerRoleMapper, RolePermissionMapper rolePermissionMapper){
        this.managerMapper = managerMapper;
        this.roleMapper = roleMapper;
        this.managerRoleMapper = managerRoleMapper;
        this.rolePermissionMapper = rolePermissionMapper;
    }

    @Override
    public PageVo<RoleVo> findAllPage(Page<Role> page, RoleDto roleDto) {
        Page<Role> rolePage = roleMapper.selectPage(page, Wrappers.lambdaQuery(Role.class)
                .likeRight(StringUtils.hasLength(roleDto.getRoleName()), Role::getRoleName, roleDto.getRoleName())
                .likeRight(roleDto.getRoleCode() != null, Role::getRoleCode, roleDto.getRoleCode())
                .eq(roleDto.getState() != null, Role::getState, roleDto.getState())
                .ge(roleDto.getStartDateTime() != null, Role::getCreateTime, roleDto.getStartDateTime())
                .lt(roleDto.getEndDateTime() != null, Role::getCreateTime, roleDto.getEndDateTime()));

        List<Role> roles = rolePage.getRecords();
        List<RoleVo> roleVos = new ArrayList<>();

        // Perform the join query to get the count of ManagerIds for each RoleId
        for (Role role : roles) {
            Long count = managerRoleMapper.selectCount(Wrappers.lambdaQuery(ManagerRole.class)
                    .eq(ManagerRole::getRoleId, role.getId()));
            RoleVo roleVo = new RoleVo();
            BeanUtils.copyProperties(role, roleVo);
            roleVo.setCount(count);
            roleVos.add(roleVo);
        }

        PageVo<RoleVo> pageVo = new PageVo<>(rolePage.getTotal(), roleVos);
        return pageVo;
    }

    @Transactional(isolation= Isolation.REPEATABLE_READ)
    @Override
    public void deleteRole(Long id) {
        //与用户表
        managerRoleMapper
                .delete(Wrappers.lambdaQuery(ManagerRole.class)
                        .eq(ManagerRole::getRoleId,id));
        //与权限表
        rolePermissionMapper
                .delete(Wrappers.lambdaQuery(RolePermission.class)
                        .eq(RolePermission::getRoleId,id));
        //删除自己
        roleMapper.deleteById(id);
    }

    @Override
    public Role findByRoleName(String roleInfo) {
        Role role = roleMapper.selectOne(Wrappers.lambdaQuery(Role.class)
                .eq(Role::getRoleName, roleInfo));
        return role;
    }

    @Override
    public Role findByRoleCode(String roleInfo) {
        Role role = roleMapper.selectOne(Wrappers.lambdaQuery(Role.class)
                .eq(Role::getRoleCode, roleInfo));
        return role;
    }

    @Override
    @Transactional
    public void updateRoleState(Role role) {
        List<ManagerRole> managerRoles = managerRoleMapper.selectList(Wrappers.lambdaQuery(ManagerRole.class)
                .eq(Objects.nonNull(role), ManagerRole::getRoleId, role.getId()));
        managerRoles.stream().forEach(e -> {
            Manager manager = managerMapper.selectOne(Wrappers.lambdaQuery(Manager.class)
                    .eq(Manager::getId, e.getManagerId()));
            manager.setState(role.getState());
            managerMapper.updateById(manager);
        });
        roleMapper.updateById(role);
    }
}
